package system_storage_service

import (
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context/contextutil"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/interface/dao"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
)

func (cls *Storage) PersistenceObject(ctx context.Context, object *model.SystemObject) errors.Error {
	if nil == object {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_GE.S_GE.PO_CT.153039 object is nil")

		return errors.ErrorServerInternalError("ISS_GE.S_GE.PO_CT.145727", "异常的传入参数")
	}

	if model.SystemObjectStatusUploading == *object.Status {
		return errors.New(errors.ErrorTypeInvalidRequest, "ISS_GE.S_GE.PO_CT.185730", "对象上传中，无法持久化存储")
	}

	if model.SystemObjectStatusFailed == *object.Status {
		return errors.New(errors.ErrorTypeInvalidRequest, "ISS_GE.S_GE.PO_CT.225733", "对象上传失败，无法持久化存储")
	}

	if !contextutil.CheckOnTransactional(ctx) {
		if err := cls.WithTransaction(ctx, func(ctx context.Context) errors.Error {
			object2, err := cls.GetObjectByCondition(ctx, dao.SystemObjectOptionWithId(object.Id), dao.SystemObjectOptionWithLock())
			if nil != err {
				return err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.PO_CT.302526", "加锁查询对象失败"))
			}

			object2.ReferCnt = pointer.New(*object2.ReferCnt + 1)

			if err := cls.object.SaveSystemObject(ctx, object2); err != nil {
				return err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.PO_CT.295832", "持久化对象失败"))
			}

			object.ReferCnt = pointer.New(*object2.ReferCnt)

			return nil
		}); nil != err {
			return err
		}

		return nil
	}

	object.ReferCnt = pointer.New(*object.ReferCnt + 1)

	if err := cls.object.SaveSystemObject(ctx, object); err != nil {
		return err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.PO_CT.542644", "持久化对象失败"))
	}

	return nil
}
